;***********************;******************
;updater.au3 by Billy 'bvierra' Vierra
;Project: Gnomoria Enhanced
;Created with ISN AutoIt Studio v. 0.8 BETA
;*****************************************

Func _updateCheck($forceCheck = 0)
	debug("Checking for update")
	Local $vDownload, $updateBuild, $uDownload
	Local $updateVersionFileLocal = $tmpdir & "/version"
	If FileExists($updateVersionFileLocal) Then FileDelete($updateVersionFileLocal)
	Local $updateTimeNow = _NowCalc()
	If _DateDiff('s', $updateTimeLastCheck, $updateTimeNow) > $updateCheckFreq Or $forceCheck = 1 Then ; If check time has passed or if force check is called
		info("Downloading version file from " & $updateVersionFile)
		$vDownload = InetGet($updateVersionFile, $updateVersionFileLocal, 1, 0)
		If $vDownload = 0 Then 
			; Version File Download failed, push off
			error("Download Failed! Will try again in 24hrs",1500,-1,-1,-2,3)
		Else
			; Received version file
			$updateBuild = IniRead($updateVersionFileLocal,"General","versionBuild","0")
			If $updateBuild > 0 Then
				; Version file downloaded successfully and has correct information in it
				If $updateBuild > $programVersionBuild Then
					; New version is available
					info("New version available for upgrade!")
					; Download new version
					Local $updateFile = $updateDir & "/gnomoriaenhanced-" & $updateBuild & ".exe"
					Local $updateFileLocal = $tmpDir * "/update.exe"
					$uDownload = InetGet($updateFile, $updateFileLocal, 1, 0)
					If $uDownload = 0 Then
						; Download of file was bad
						error("Download error from " & $updateFile)
					Else
						; Download of file was good
						If @compiled Then
							; Verify we are compiled, if not we actually have nothing to upgrade
							FileDelete($myPath & "/gnomoriaenhanced.exe")
							FileMove($updateFileLocal,$myPath & "/gnomoriaenhanced.exe")
							_ScriptRestart()
						EndIf
					EndIf
				Else
					; No new version available
					info("Running latest version")
				EndIf
			Else
				; Update version has bad information
				warn("Version file appears corrupt, will try again later")
			EndIf
		EndIf	
		FileDelete($updateVersionFileLocal)
		$updateTimeLastCheck = $updateTimeNow ; Set last check time to now
		IniWrite($configFile,"General","updateTimeLastCheck",$updateTimeLastCheck) ; Write last check time to ini
		_updateSetTimer() ; Set the timer for auto update
	Else
		debug("Update check time is not ready " & $updateTimeNow & "|" & $updateTimeLastCheck & "|" & $updateCheckFreq)
	EndIf
EndFunc

Func _updateSetTimer()
	Local $updateNextCheckTime = _DateAdd('s',$updateCheckFreq,$updateTimeLastCheck)
	$updateNextCheck = _DateDiff('s',_NowCalc(),$updateNextCheckTime)	
	If  $updateNextCheck < 300 Then
		debug("Next scheduled update check is in less than 5min, checking now")
		_updateCheck(1)
	EndIf
	$updateTimer = TimerInit()
	$updateNextCheck = $updateNextCheck * 1000
EndFunc